<?php

class stYoutubeToolboxController extends stcontroller_2_1 {

    public function __construct($config) {
        parent::__construct($config);
        session_start();
        
    }

    public function loadAdminCss() {
        echo '<link href="' . $this->config ['backendCss'] . 'prettyphoto/prettyPhoto.css" rel="stylesheet" type="text/css" />' . "\n";
    }

    public function loadAdminScript() {
//        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'jquery.prettyPhoto.js"></script>';
        echo '<script type="text/javascript" src="' . $this->config ['backendScript'] . 'stYoutubeToolboxCustom.js"></script>';
        echo '<script type="text/javascript" src="http://www.google.com/jsapi"></script>';
        echo '<script type="text/javascript">';
        echo "google.load('visualization', '1', {packages: ['corechart']});";
        echo '</script>';
    }

    public function loadCss() {
        //this is function import javascript
        parent::loadCss();
    }

    public function loadScript() {
        //this is function import javascript
        parent::loadScript();
    }

    public function activationPlugin() {
        // put your activation code here
        global $wpdb;
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

        $table = $wpdb->prefix . "st_youtubeplaylist";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `playlist_id` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `name` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `youtube_user` varchar(64) COLLATE utf8_unicode_ci NOT NULL,            
              `cdate` datetime NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
            ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_youtubevideo";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `video_id` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `youtube_user` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `title` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `description` text COLLATE utf8_unicode_ci DEFAULT NULL,
              `category` text COLLATE utf8_unicode_ci DEFAULT NULL,
              `tag` text COLLATE utf8_unicode_ci DEFAULT NULL,
              `duration` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
              `view_count` int(11) NOT NULL,
              `rating` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `geo_location` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `record_on` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `thumbnail_url` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `cdate` datetime NOT NULL,
              `favorite` smallint(6) NOT NULL DEFAULT '0',
              `can_delete` smallint(6) NOT NULL DEFAULT '1',
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
            ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_youtube_playlist_video";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `video_id` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `playlist_id` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
            ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_youtube_statistic";
        $structure = "CREATE TABLE IF NOT EXISTS `$table` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `video_id` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `view` int(11) NOT NULL DEFAULT '0',
              `cdate` datetime NOT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
            ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_youtube_comment";
        $structure = "CREATE TABLE IF NOT EXISTS `$table` (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `video_id` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `comment_id` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `title` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `content` text COLLATE utf8_unicode_ci NOT NULL,
              `author` varchar(225) COLLATE utf8_unicode_ci NOT NULL,
              `link` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `updated` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
            ";
        dbDelta($structure);

        $table = $wpdb->prefix . "st_youtube_user";
        $structure = "CREATE TABLE IF NOT EXISTS $table (
              `id` int(11) NOT NULL AUTO_INCREMENT,
              `user_id` int(11) NOT NULL,
              `user_name` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_password` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              `user_channel` varchar(225) COLLATE utf8_unicode_ci DEFAULT NULL,
              PRIMARY KEY (`id`)
            ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ;
            ";
        dbDelta($structure);
    }

    public function deactivationPlugin() {
        // put your deactivation code here
//            global $wpdb;
//            $table = $wpdb->prefix."st_stYoutubeToolbox";
//            $query = "DROP TABLE $table";
//            $wpdb->query($query);
    }

    public function registerView() {
        $views = array(
            'youtubeCronjobStatistic' => 'default_theme',
            'youtubeCronjobComment' => 'default_theme',
            'getImagePreview' => 'default_theme'
        );
        $this->setView($views);
    }

    public function index() {
        if ($_REQUEST['status'] == 200) {
            $this->youtubeReturn($_REQUEST['id']);

            echo '<script type="text/javascript">';
            echo "stYoutubeToolboxCustom.stRedirect('" . admin_url('/admin.php?page=' . $this->config['plugin_name'] . '&action=youtubeList') . "');";
            echo '</script>';
        }

        $option = $this->option;
        //initialize variable to view
        $this->view->option = $option;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'General settings';
        $this->view->iconNew = '';
        $this->view->viewNew = '';

        if ($_POST['handle']) {
            $st_language = isset($_POST['st_language']) ? $_POST['st_language'] : $option['st_language'];

            $data = array(
                'st_language' => $st_language
            );
            $this->updateOption($data);
        }
    }

    public function youtubeSetting() {        
        $youtubeUser_model = $this->loadmodel("stYoutubeToolboxuser");
        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {
            if ($youtubeUser_model->deleteRecords($_REQUEST['id'])){
                $arg = array(
                    'status'    => 'success',
                    'message'   => __('Delete successful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
            else{
                $arg = array(
                    'status'    => 'error',
                    'message'   => __('Delete unsuccessful', $config['plugin_name'])
                );
                echo $this->functions->sendMessage(json_encode($arg));
            }
        }

        $args = array();

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);
        $user_id = get_current_user_id();
        $args['where'] = " user_id = $user_id ";
        $results = $youtubeUser_model->getRecords($args);
        $total = $youtubeUser_model->countRecords();

        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            'id' => __('ID', $this->config['plugin_name']),
            'user_name' => __('User Name', $this->config['plugin_name']),
            'user_channel' => __('Channel', $this->config['plugin_name']),
            'short_action' => __('Action', $this->config['plugin_name']),
        );
        register_column_headers('stYoutubeToolbox_User', $columns);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Youtube User lists';
        $this->view->iconNew = 'Add new YouTube account';
        $this->view->viewNew = 'youtubeUserEdit';
    }

    public function youtubeUserEdit() {
        $youtubeUser_model = $this->loadmodel("stYoutubeToolboxuser");
        $results = '';
        if (isset($_REQUEST['id'])) {
            $id = $_REQUEST['id'];
            $args = array();
            $args['where'] = " `id` = $id";
            $results = $youtubeUser_model->getRecords($args);
        }
        $result = $results[0];
        $user_id = get_current_user_id();
        //initialize variable to view
        $this->view->result = $result;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'New User';
        $this->view->headTitle2 = 'Edit User';
        $this->view->user_id = $user_id;

        // Handle post
        if ($_POST['data']) {
            $message = $youtubeUser_model->saveYoutubeUser($_POST['data']);
//            echo $this->functions->sendMessage(json_encode($message), 'youtubeSetting');
            echo '|*|'.json_encode($message);
            die;
            
        }


    }

    public function youtubeList() {
    	$stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $filter = isset($_POST['filter']) ? $_POST['filter'] : 'all';
        $userFilter = isset($_POST['userFilter']) ? $_POST['userFilter'] : 0;
        if ($_POST['sync'] == 1) {
            require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
            $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
            $stYoutubeToolbox->syncVideo();
        }

        // short action handle
        if ($_REQUEST['short_action'] == 'delete') {
            if ($stYoutubeToolboxvideo_model->deleteRecords($_REQUEST['id']))
                echo stfunctions_2_1::sendMessage(__('Delete successful ', $this->config['plugin_name']));
            else
                echo stfunctions_2_1::sendMessage(__('Delete fail', $this->config['plugin_name']));
        }

        if ($_REQUEST['short_action'] == 'remove_favorite') {
            if ($stYoutubeToolboxvideo_model->deleteRecords($_REQUEST['id']))
                echo stfunctions_2_1::sendMessage(__('Remove favorite successful', $this->config['plugin_name']));
            else
                echo stfunctions_2_1::sendMessage(__('Remove favorite fail', $this->config['plugin_name']));
        }

        $args = array();
        $args['fields'] = array("video.*, GROUP_CONCAT(' ',playlist.name) playlist_name, playlist.playlist_id playlist_id");
        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;

        $sort = $_REQUEST['sort'] ? $_REQUEST['sort'] : 0;
        $sort_type = $_REQUEST['sort_type'] ? $_REQUEST['sort_type'] : 0;
        if ($_REQUEST['sort']) {
            $args['order'] = array($sort, $sort_type);
        }
        $args['limit'] = array($start, $limit);
        $args['group_by'] = 'id';
        $where = array();
        if ($filter != 'all') {
            switch ($filter) {
                case 'favorite':
                    $where[] = ' video.favorite = 1';
                    break;

                default:
                    //$args['where'] = " playlist.playlist_id like('$filter') ";
                    $where[] = ' video.can_delete = 1';
                    break;
            }
            //$args['where'] = '';
        }

        if ($userFilter != 0) {
            $where[] = ' video.user_id = '.$userFilter;
            //$args['where'] = '';
        }
        $user_id = get_current_user_id();
        $where[] = " user.user_id = $user_id ";
        $args['where'] = implode(' AND ', $where);

        $results = $stYoutubeToolboxvideo_model->getRecords($args);
        $args['limit'] = array();
        $total = $stYoutubeToolboxvideo_model->countRecords($args);
        $stYoutubeToolboxFunctions = new stYoutubeToolboxFunctions($this->config);
        $pagination = $stYoutubeToolboxFunctions->pagination($start, $limit, $total, $cur_page, $this->actionName);

        $columns = array(
            //'id'  => __('ID', $this->config['plugin_name']),
            //'youtube_user'  => __('User', $this->config['plugin_name']),
            'title' => __('Title', $this->config['plugin_name']),
            'thumbnail_url' => __('Images', $this->config['plugin_name']),
            'description' => __('Description', $this->config['plugin_name']),
            'category' => __('Categories', $this->config['plugin_name']),
            //'tag'           => __('Tags', $this->config['plugin_name']),
            //'duration'      => __('Duration', $this->config['plugin_name']),
            'view_count' => __('View', $this->config['plugin_name']),
            'playlist_name' => __('Video type', $this->config['plugin_name']),
            'favorite'      => __('Publish to', $this->config['plugin_name']),
                //'rating'        => __('Rating', $this->config['plugin_name']),
                //'cdate'         => __('Create date', $this->config['plugin_name']),
                //'short_action' => __('Action', $this->config['plugin_name']),
        );
        register_column_headers('stYoutubeToolbox_st_youtubevideo', $columns);

        $stYoutubeToolboxplaylist_model = $this->loadmodel("stYoutubeToolboxplaylist");
        $playlists = $stYoutubeToolboxplaylist_model->getRecords();

        $args = array();
        $user_id = get_current_user_id();
        $args['where'] = " user_id = $user_id ";
        $youtubeUser_model = $this->loadmodel("stYoutubeToolboxuser");
        $users = $youtubeUser_model->getRecords($args);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->permission = $this->functions->getPermission();
        $this->view->permission_twitter = $this->functions->getPermission('stTwitterToolbox');
        $this->view->option_facebook = get_option("wall_publish_option");
        $this->view->option_twitter = $this->functions->cronjob_get_option('stTwitterToolbox_1_settings', $user_id);
        $this->view->pagination = $pagination;
        $this->view->playlists = $playlists;
        $this->view->filter = $filter;
        $this->view->userFilter = $userFilter;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Video list';
        $this->view->iconNew = 'Synchronize with YouTube';
        $this->view->viewNew = 'youtubeList';
        $this->view->dataNew = array('sync' => 1);
        $arg = array(
            'status' => 'success',
            'message' => __('Update video successful', $config['plugin_name'])
        );
        $this->view->messageNew = json_encode($arg);
        $this->view->users = $users;
    }

    public function youtubeEdit() {

        $stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $results = '';
        if (isset($_REQUEST['id']) || isset($_POST['data']['id'])) {
            $id = $_REQUEST['id'];
            if (isset($_POST['data']['id']))
                $id = $_POST['data']['id'];
            $args = array();
            $args['fields'] = array("video.user_id user_id, video.*, playlist.name playlist_name, playlist.playlist_id playlist_id");
            $args['where'] = " video.id = $id";
            $results = $stYoutubeToolboxvideo_model->getRecords($args);
        }
        $result = $results[0];
        $video_playlist = array();
        if (is_array($results)) {
            foreach ($results as $value) {
                $video_playlist[] = $value->playlist_id;
            }
        }
        $video_id = $result->video_id;
        $disable = '';
        if ($result->can_delete == 0) {
            $disable = 'disabled';
        }

        $stYoutubeToolboxplaylist_model = $this->loadmodel("stYoutubeToolboxplaylist");
        $args = array();
        $args['where'] = " user_id = {$result->user_id}";
        $playlists = $stYoutubeToolboxplaylist_model->getRecords($args);
        //initialize variable to view
        $this->view->result = $result;
        $this->view->playlists = $playlists;
        $this->view->video_playlist = $video_playlist;
        $this->view->disable = $disable;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'New video';
        $this->view->headTitle2 = 'Edit video';

        // Handle post
        if ($_POST['data']) {
            require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
            $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
            $data = $_POST['data'];
            $video_id = $data['video_id'];
            $data_old = (array) $results[0];
            $data_old['playlist'] = $video_playlist;
            $stYoutubeToolbox->editVideo($video_id, $data, $playlists, $data_old);
            $stYoutubeToolboxvideo_model->updateVideo($_POST['data'], $disable);
        }
    }

    public function youtubeUpload() {
        
        ////////////////////
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Upload video';        
        $this->view->users = $users;

        if ($_POST['handle'] == 'step1') {
            $data = $_POST['data'];
            require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
            $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
            $tokenArray = $stYoutubeToolbox->getTokenUpload($data);
            $tokenValue = $tokenArray['token'];
            $postUrl = $tokenArray['url'];
?>
            <input type="hidden" value="<?php echo $tokenValue ?>" name="token" id="token">
<?php
            echo '|**|' . $postUrl;
            die;
        }
    }

    public function youtubeUploadForm() {
//            $this->view->headIcon = 'icon_re';
//            $this->view->headTitle1 = 'Upload video';

        $args = array();
        $user_id = get_current_user_id();
        $args['where'] = " user_id = $user_id ";
        $youtubeUser_model = $this->loadmodel("stYoutubeToolboxuser");
        $users = $youtubeUser_model->getRecords($args);
        $this->view->users = $users;
        if ($_REQUEST['status'] == 200) {
            $this->youtubeReturn($_REQUEST['video_id']);
            $this->view->uploadStatus = 'done';
            $this->view->videoId = $_REQUEST['video_id'];
        }
        if ($_POST['handle'] == 'step1') {
            $data = $_POST['data'];
            require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
            $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
            $tokenArray = $stYoutubeToolbox->getTokenUpload($data);
            $tokenValue = $tokenArray['token'];
            $postUrl = $tokenArray['url'];
//            $token = time()+(2*60*60);
//            setcookie("LOGIN_SECURITY_TOKEN", $data['user_id'], $token);
            $_SESSION['userUpload'] = $data['user_id'];
?>
            <input type="hidden" value="<?php echo $tokenValue ?>" name="token" id="token">
<?php
            echo '|**|' . $postUrl;
            die;
        }
    }

    public function youtubeReturn($video_id) {
        $stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
        $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
        $user_id = $_SESSION['userUpload'];
        $videoEntry = $stYoutubeToolbox->getVideo($video_id, $user_id);
        $videoEntry->setMajorProtocolVersion(2);

        $videoUploads['video_entry'] = array($videoEntry);
        $videoUploads['user_id'] = $user_id;
        $stYoutubeToolboxvideo_model->savestYoutubeToolboxVideo($videoUploads);
    }

    public function youtubeDashboard() {
        $stYoutubeToolboxdashboard_model = $this->loadmodel("stYoutubeToolboxdashboard");
        $stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");

        $totalView = $stYoutubeToolboxdashboard_model->getTotalView();
        $mostVideo = $stYoutubeToolboxdashboard_model->getMostViewVideo();
        $mostCommentVideo = $stYoutubeToolboxdashboard_model->getMostCommentVideo();
        $args = array();
        $args['fields'] = array("video.*, GROUP_CONCAT(' ',playlist.name) playlist_name, playlist.playlist_id playlist_id");
        $args['group_by'] = 'id';
        ////////////
        $user_id = get_current_user_id();
        $args['where'] = " user.user_id = $user_id";
        ///////////////
        $totalVideo = $stYoutubeToolboxvideo_model->countRecords($args);
        $viewYesterdayPlusYesterdaybefore = $stYoutubeToolboxdashboard_model->getViewYesterdayAndYesterBefore();

        //initialize variable to view
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'YouTube Dashboard';
        $this->view->iconNew = '';
        $this->view->viewNew = '';
        $this->view->viewYesterdayPlusYesterdaybefore = $viewYesterdayPlusYesterdaybefore;
        $this->view->totalVideo = $totalVideo;
        $this->view->totalView = $totalView;
        $this->view->mostCommentVideo = $mostCommentVideo;
        $this->view->mostVideo = $mostVideo;
    }

    public function youtubeStatistics() {
        $filter = isset($_POST['filter']) ? $_POST['filter'] : 'all';
        $userFilter = isset($_POST['userFilter']) ? $_POST['userFilter'] : 0;
        $this->config['per_page'] = 30;
        // Prepare Chart data
        $month = !isset($_POST['month']) ? date('n', time()) : $_POST['month'];
        $month = ($month < 10) ? "0" . $month : $month;
        $year = empty($_POST['year']) ? date('Y', time()) : $_POST['year'];

        if (intval($month) == 0) {
            $month = 12;
            $year -= 1;
        }

        if (intval($month) == 13) {
            $month = "01";
            $year += 1;
        }

        $start_day = mktime(0, 0, 0, $month, 1, $year);
        $day_count = date('t', $start_day);
        $end_day = mktime(0, 0, 0, $month, $day_count, $year);

        $start_month = date('n', $start_day);
        $start_year = date('Y', $start_day);

        $stYoutubeToolboxstatistics_model = $this->loadmodel("stYoutubeToolboxstatistics");

        $args = array();

        $args['fields'] = array('sum(statistic.view) view, statistic.cdate cdate');
        $args['fields'][] = 'MONTH(statistic.cdate) month, YEAR(statistic.cdate) year, DAY(statistic.cdate) day';
        $args['where'] = " MONTH(statistic.cdate) = $start_month AND YEAR(statistic.cdate) = $start_year";
        $args['order'] = array('statistic.cdate', 'asc');
        $args['group_by'] = ' DAY(statistic.cdate) ';
        if ($filter != 'all') {
            $args['where'] .= " AND video.video_id like('$filter')";
            $args['fields'][] = "video.thumbnail_url thumbnail, video.title title";
        }
        ////////////
        $user_id = get_current_user_id();
        $args['where'] .= " AND user.user_id = $user_id";
        ///////////////
        if ($userFilter != 0) {
            $args['where'] .= " AND statistic.user_id = $userFilter";
//            $where[] = ' video.user_id = '.$userFilter;
            //$args['where'] = '';
        }
        $results = $stYoutubeToolboxstatistics_model->getRecords($args);
        $total = $stYoutubeToolboxstatistics_model->countRecords();

        $columns = array(
            'cdate' => __('Date', $this->config['plugin_name']),
            'view' => __('View', $this->config['plugin_name'])
        );
        register_column_headers('stYoutubeToolbox_statistic', $columns);

        $dates_in_history = $stYoutubeToolboxstatistics_model->getDate();

        $date_history = array();
        foreach ($dates_in_history as $value) {
            $day_temp = ($value->day < 10) ? "0" . $value->day : $value->day;
            $month_temp = ($value->month < 10) ? "0" . $value->month : $value->month;
            $date_history[] = $day_temp . '-' . $month_temp . '-' . $value->year;
        }

        $stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $args = array();
        $args['custom_query'] = "SELECT * FROM {$stYoutubeToolboxvideo_model->prefix}st_youtubevideo";
        $videos = $stYoutubeToolboxvideo_model->getRecords($args);

        $args = array();
        $args['custom_query'] = "SELECT * FROM {$stYoutubeToolboxvideo_model->prefix}st_youtubevideo
            WHERE video_id like('$filter')
            ";
        $video_filter = $stYoutubeToolboxvideo_model->getRecords($args);

        $args = array();
        $user_id = get_current_user_id();
        $args['where'] = " user_id = $user_id ";
        $youtubeUser_model = $this->loadmodel("stYoutubeToolboxuser");
        $users = $youtubeUser_model->getRecords($args);

        //initialize variable to view
        $this->view->results = $results;
        $this->view->month = $month;
        $this->view->year = $year;
        $this->view->day_count = $day_count;
        $this->view->end_day = $end_day;
        $this->view->start_day = $start_day;
        $this->view->date_history = $date_history;
        $this->view->videos = $videos;
        $this->view->filter = $filter;
        $this->view->video_filter = $video_filter;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Statistics';
        $this->view->users = $users;
        $this->view->userFilter = $userFilter;
    }

    public function youtubeComments() {
        $filter = isset($_POST['filter']) ? $_POST['filter'] : 'all';
        $stYoutubeToolboxcomment_model = $this->loadmodel("stYoutubeToolboxcomment");

        $args = array();
        $args['fields'] = array('video.*, video.title video_title, video.video_id video_id,
            video.thumbnail_url thumbnail_url, comment.*, comment.title title,
            comment.author author, comment.content content'
        );
        $args['order'] = array('video.video_id', 'desc');
        $where = array();
        if ($filter != 'all') {
            $where[] = " video.video_id like('$filter')";
        }

        $cur_page = $_REQUEST['cur_page'] ? $_REQUEST['cur_page'] : 1;
        $limit = $this->config['per_page'];
        $start = ($cur_page - 1) * $limit;
        $args['limit'] = array($start, $limit);

        ////////////
        $user_id = get_current_user_id();
        $where[] = " user.user_id = $user_id";
        $args['where'] = implode('AND', $where);
        ///////////////

        $results = $stYoutubeToolboxcomment_model->getRecords($args);
        $args['limit'] = array();
        $total = $stYoutubeToolboxcomment_model->countRecords($args);
        $pagination = $this->functions->pagination($start, $limit, $total, $cur_page, $this->actionName);
        $args['group_by'] = 'video.video_id';
        $args['where'] = '';
        $videos = $stYoutubeToolboxcomment_model->getRecords($args);

        $columns = array(
            'thumbnail_url' => __('Video', $this->config['plugin_name']),
            'author' => __('Author', $this->config['plugin_name']),
            'title' => __('Title', $this->config['plugin_name']),
            'content' => __('Content', $this->config['plugin_name'])
//            'comment.title' => __('Date', $this->config['plugin_name']),
//            'comment.title' => __('Date', $this->config['plugin_name']),
//            'cdate' => __('Date', $this->config['plugin_name']),
//            'view' => __('View', $this->config['plugin_name'])
        );
        register_column_headers('stYoutubeToolbox_comment', $columns);
        
        //initialize variable to view
        $this->view->results = $results;
        $this->view->pagination = $pagination;
        $this->view->filter = $filter;
        $this->view->videos = $videos;
        $this->view->headIcon = 'icon_re';
        $this->view->headTitle1 = 'Comments';
    }

    public function youtubeDetail() {

        $stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $results = '';
        if (isset($_REQUEST['id']) || isset($_POST['data']['id'])) {
            $id = $_REQUEST['id'];
            if (isset($_POST['data']['id']))
                $id = $_POST['data']['id'];
            $args = array();
            $args['fields'] = array("video.*, playlist.name playlist_name, playlist.playlist_id playlist_id");
            $args['where'] = " video.id = $id";
            $results = $stYoutubeToolboxvideo_model->getRecords($args);
        }
        $result = $results[0];
        $video_playlist = array();
        if (is_array($results)) {
            foreach ($results as $value) {
                $video_playlist[] = $value->playlist_id;
            }
        }
        $video_id = $result->video_id;

        $stYoutubeToolboxplaylist_model = $this->loadmodel("stYoutubeToolboxplaylist");
        $playlists = $stYoutubeToolboxplaylist_model->getRecords();
        //initialize variable to view
        $this->view->result = $result;
        $this->view->playlists = $playlists;
        $this->view->video_playlist = $video_playlist;
        $this->view->headIcon = 'icon_re';
    }

    public function youtubeCronjobStatistic() {
        require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
        $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
        $stYoutubeToolbox->cronjobStatistic();
        die;
    }

    public function youtubeCronjobComment() {
        require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
        $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
        $stYoutubeToolbox->cronjobGetComment();
        die;
    }

    public function getImagePreview() {
        $user_name = basename($this->option['youtube_channel']);
        $link = disguise_curl("http://gdata.youtube.com/feeds/api/users/{$user_name}/uploads/{$_REQUEST['video_id']}");

        if (strpos($link, 'yes') > 0) {
            echo '|**|';
            echo 'false';
            echo '|**|';
        } else {
            require_once $this->config['pluginDir'] . 'stYoutubeToolboxclass.php';
            $stYoutubeToolbox = new stYoutubeToolboxclass($this->config, $this->option);
            $user_id = $_SESSION['userUpload'];
            $videoEntry = $stYoutubeToolbox->getVideo($_REQUEST['video_id'], $user_id);
//            $videoEntry = $stYoutubeToolbox->getVideo($_REQUEST['video_id']);
            $thumbnail = $videoEntry->getVideoThumbnails();
            $data = array();
            foreach ($thumbnail as $value) {
                $data[] = $value['url'];
            }
            echo '|**|';
            echo json_encode($data);
            echo '|**|';
        }
        die;
    }

    
}
?>